from fastapi import APIRouter, HTTPException
from demo.services.device_service import DeviceService
from demo.websocket.manager import ConnectionManager

router = APIRouter()


def setup_routes(router: APIRouter, connection_manager: ConnectionManager, device_service: DeviceService):
    """设置路由"""

    @router.get("/")
    async def root():
        return {"message": "设备管理与AI对话服务"}

    @router.get("/status")
    async def get_status():
        """获取服务状态"""
        return {
            "active_devices": len(connection_manager.active_device_connections),
            "active_sessions": len(connection_manager.chat_sessions),
            "device_ids": connection_manager.get_connected_devices()
        }

    @router.get("/devices")
    async def get_devices():
        """获取所有设备信息"""
        try:
            devices = await device_service.list_devices()
            return {"devices": devices}
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"获取设备列表失败: {str(e)}")

    @router.get("/devices/{device_id}")
    async def get_device(device_id: str):
        """获取特定设备信息"""
        device = await device_service.get_device(device_id)
        if not device:
            raise HTTPException(status_code=404, detail="设备未找到")
        return {"device": device}

    @router.get("/devices/{device_id}/chat-history")
    async def get_chat_history(device_id: str):
        """获取设备对话历史"""
        chat_history = connection_manager.get_chat_history(device_id)
        return {"device_id": device_id, "chat_history": chat_history}